import {Component} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Store} from "@ngrx/store";
import {nextCurrent, setStepData} from "../store/actions/step.actions";
import {Utils} from "../common/utils";
import {pairwise} from "rxjs";

interface ListItem {
  age: number;
  gender: string;
  id: number;
  name: string;
}

@Component({
  selector: 'app-step3',
  templateUrl: './step3.component.html',
  styleUrls: ['./step3.component.less']
})
export class Step3Component {
  showForm = {
    moreSelect: false,
    gangedSelect: false
  }
  isLoading = false;
  // male
  maleOptionList: ListItem[] = [];
  selectedMale: {
    id: number | null
  } = {
    id: null
  };
  // female
  options1: any;
  options2: any;
  selectedOption1: {
    id: number | null
  } = {
    id: null
  };
  selectedOption2: {
    id: number | null
  } = {
    id: null
  };
  step3Click: boolean = false;

  constructor(
    private http: HttpClient,
    private store: Store<{ step: any }>) {
    store.select('step').pipe(pairwise()).subscribe(([previousValue, currentValue]) => {
      if(!(previousValue.current === 1 &&
        currentValue.current === 2)) return
      console.log('执行step3')
      const res = currentValue;
      const initStatus = () => {
        this.showForm.moreSelect = false
        this.showForm.gangedSelect = false
      }
      initStatus()
      const step2Data = res.stepData.step2
      const init = () => {
        if (step2Data['maleClothes']?.includes('a1')) {
          this.getMaleData();
          this.showForm.moreSelect = true
        }
        if (step2Data['femaleClothes']) {
          const step2DataA = step2Data['femaleClothes']?.find((item: { key: string; }) => item.key === 'A')
          if (step2DataA?.value === true) {
            this.getOptions1();
            this.showForm.gangedSelect = true
          }
        }
        if (this.showForm.moreSelect === false && this.showForm.gangedSelect === false) {
          this.store.dispatch(setStepData({data: {}}))
          this.store.dispatch(nextCurrent())
        }
      }
      if (res.current === 2) {
        init()
      }
    });
  }

  ngOnInit(): void {
    // this.testMockConnect()
    this.step3Click = false
    console.log('this.selectedOption1', this.selectedOption1)
  }

  private testMockConnect() {
    this.http.get(`/api/test`)
      .subscribe((response: any) => {
        console.log(response)
      });
  }

  getMaleData(): void {
    const offset = this.maleOptionList.length;
    const limit = 10;
    this.isLoading = true;
    // I used a Get Request earlier, but it gave me a 404 error,
    // The solution is to use regular expressions, in my case Post requests.
    this.http.post<{ list: ListItem[] }>(`/api/loadmore`, {offset, limit})
      .subscribe((response) => {
        console.log(response)
        this.isLoading = false;
        this.maleOptionList = [...this.maleOptionList, ...response.list]
      });
  }

  getOptions1(): void {
    this.isLoading = true;
    this.http.post<{ options: { id: number, name: string }[] }>(`/api/getOptions1`, {})
      .subscribe((response) => {
        console.log(response.options)
        this.isLoading = false;
        this.options1 = response.options
      });
  }

  getOptions2(): void {
    console.log(this.selectedOption1)
    this.selectedOption2 = {id: null}
    const id = this.selectedOption1.id
    this.http.post(`/api/getOptions2`, {id})
      .subscribe((response) => {
        console.log(response)
        this.isLoading = false;
        this.options2 = response
      });
  }

  getStep3Data() {
    let data: { [key: string]: any } = {}
    if (this.showForm.moreSelect) {
      data['moreSelected'] = Utils.deepCopyObject(this.selectedMale)
    }
    if (this.showForm.gangedSelect) {
      data['gangedSelect'] = {
        option1: Utils.deepCopyObject(this.selectedOption1),
        option2: Utils.deepCopyObject(this.selectedOption2),
      }
    }
    return {
      data
    }
  }

  checkStep3Data() {
    console.log(this.selectedMale,'this.selectedMale')
    this.step3Click = true
    if (this.showForm.moreSelect) {
      return this.selectedMale['id'] !== null
    }
    if (this.showForm.gangedSelect) {
      return this.selectedOption1['id'] !== null &&
        this.selectedOption2['id'] !== null
    }
    return true
  }
}
